package com.cskaoyan.order.service.impl;

import com.cskaoyan.mall.order.constant.OrderRetCode;
import com.cskaoyan.order.converter.OrderConverter;
import com.cskaoyan.order.dal.entitys.Order;
import com.cskaoyan.order.dal.entitys.OrderItem;
import com.cskaoyan.order.dal.entitys.OrderShipping;
import com.cskaoyan.order.dal.persistence.OrderItemMapper;
import com.cskaoyan.order.dal.persistence.OrderMapper;
import com.cskaoyan.order.dal.persistence.OrderShippingMapper;
import com.cskaoyan.order.dto.*;
import com.cskaoyan.order.service.OrderQueryService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * OrderQueryServiceImpl
 *
 * @param
 * @return
 * @2022/4/22
 **/
@Service
public class OrderQueryServiceImpl implements OrderQueryService {
    @Autowired
    OrderConverter orderConverter;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderItemMapper orderItemMapper;
    @Autowired
    OrderShippingMapper orderShippingMapper;
    /**
     * 查询指定用户下订单总数
     * @param request
     * @return
     */
    @Override
    public OrderCountResponse orderCount(OrderCountRequest request) {
        OrderCountResponse response=new OrderCountResponse();

        try {
            request.requestCheck();
            Long userId = request.getUserId();
            Example example = new Example(Order.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("user_id",userId);
            List<Order> orders = orderMapper.selectByExample(example);
            response.setCount(orders.size());
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(OrderRetCode.DB_EXCEPTION.getCode());
            response.setMsg(OrderRetCode.DB_EXCEPTION.getMessage());
        }
        return response;

    }

    /**
     * 查询当前用户的历史订单列表
     * @param request
     * @return
     */
    @Override
    public OrderListResponse orderList(OrderListRequest request) {

        OrderListResponse response=new OrderListResponse();

        try {
            request.requestCheck();
            Long userId = request.getUserId();
            List<OrderDetailInfo> result=new ArrayList<>();
//            1.parameters- userId

            Example example = new Example(Order.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("userId",userId);
//            2.example
            List<Order> orders = orderMapper.selectByExample(example);
//            for (Order order : orders) {
//                OrderDetailInfo info = orderConverter.order2detail(order);
//                System.out.println("info = " + info);
//                result.add(info);
//            }


            for (Order order : orders) {
                OrderDetailInfo info=new OrderDetailInfo();
                info.setOrderId(order.getOrderId());
                info.setPayment(order.getPayment());
                info.setStatus(order.getStatus());

                info.setPostFee(order.getPostFee());
                info.setCreateTime(order.getCreateTime());
                info.setUpdateTime(order.getUpdateTime());
                info.setConsignTime(order.getConsignTime());
                info.setEndTime(order.getEndTime());
                info.setCloseTime(order.getCloseTime());
                info.setShippingName(order.getShippingName());
                info.setShippingCode(order.getShippingCode());
                info.setUserId(order.getUserId());
                info.setBuyerMessage(order.getBuyerMessage());
                info.setBuyerNick(order.getBuyerNick());
                info.setBuyerComment(order.getBuyerComment());

                Example example1=new Example(OrderItem.class);
                example1.createCriteria().andEqualTo("orderId",order.getOrderId());
                List<OrderItem> orderItems = orderItemMapper.selectByExample(example1);
                List<OrderItemDto> orderItemDtos=new ArrayList<>();
                OrderShippingDto orderShippingDto=new OrderShippingDto();
                for (OrderItem orderItem : orderItems) {
                    OrderItemDto orderItemDto1 = orderConverter.item2dto(orderItem);
                    orderItemDtos.add(orderItemDto1);
                }
                OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(order);
                 orderShippingDto = orderConverter.shipping2dto(orderShipping);
                info.setOrderItemDto(orderItemDtos);
                info.setOrderShippingDto(orderShippingDto);
                result.add(info);
            }



//            3.page
            PageInfo<OrderDetailInfo> pageInfo=new PageInfo<>(result);
            int pageSize = pageInfo.getPageSize();

//            int pages = pageInfo.getPages();
////        Integer total = ((Integer) pageInfo.getTotal());
//            int pageNum = pageInfo.getPageNum();
//            result.setList(marketCoupons);
//            result.setPage(pageNum);
//            result.setPages(pages);
//            result.setTotal((int) pageInfo.getTotal());
//            result.setLimit(pageInfo.getSize());

            response.setTotal((long) orders.size());
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

            response.setData(result);

            System.out.println("result = " + result);

        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(OrderRetCode.DB_EXCEPTION.getCode());
            response.setMsg(OrderRetCode.DB_EXCEPTION.getMessage());
//            REQUISITE_PARAMETER_NOT_EXIST parameter can not be null!!!!
        }
        return response;
    }


    /**
     * 查询订单明细
     * @param request
     * @return
     */
    @Override

    public OrderDetailResponse orderDetail(OrderDetailRequest request) {
        OrderDetailResponse response=new OrderDetailResponse();
        try {
            request.requestCheck();
            String orderId = request.getOrderId();
            Order order = orderMapper.selectByPrimaryKey(orderId);
            response = orderConverter.order2res(order);
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());
            OrderShipping orderShipping = orderShippingMapper.selectByPrimaryKey(order.getOrderId());

            OrderShippingDto orderShippingDto = orderConverter.shipping2dto(orderShipping);
            List<OrderItemDto> goodsList=new ArrayList<>();
            Example example=new Example(OrderItem.class);
             example.createCriteria().andEqualTo("orderId", order.getOrderId());

            List<OrderItem> orderItems = orderItemMapper.selectByExample(example);
            System.out.println("orderItems = " + orderItems);
            BigDecimal orderTotal=orderItems.get(0).getTotalFee();
            for (OrderItem orderItem : orderItems) {
                OrderItemDto orderItemDto = orderConverter.item2dto(orderItem);
                goodsList.add(orderItemDto);
                Integer num = orderItem.getNum();
//                BigDecimal price = orderItem.getPrice();
//                BigDecimal multiply = price.multiply(new BigDecimal(num));
//                System.out.println("multiply = " + multiply);
                BigDecimal totalFee = orderItemDto.getTotalFee();
                orderTotal.add(totalFee);
            }
            response.setTel(orderShipping.getReceiverPhone());
            response.setStreetName(orderShipping.getReceiverAddress());
            response.setOrderTotal(orderTotal);
            System.out.println("orderTotal = " + orderTotal);
            response.setGoodsList(goodsList);
            response.setOrderShippingDto(orderShippingDto);
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(OrderRetCode.DB_EXCEPTION.getCode());
            response.setMsg(OrderRetCode.DB_EXCEPTION.getMessage());
        }
        System.out.println("response = " + response);
        return response;
    }
    /**
     * 查询订单条目
     * @param request
     * @return
     */
    @Override
    public OrderItemResponse orderItem(OrderItemRequest request) {

        OrderItemResponse response=new OrderItemResponse();

        try {
            request.requestCheck();
            String orderItemId = request.getOrderItemId();
            OrderItem orderItem = orderItemMapper.selectByPrimaryKey(orderItemId);
            response=orderConverter.item2res(orderItem);
            response.setCode(OrderRetCode.SUCCESS.getCode());
            response.setMsg(OrderRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(OrderRetCode.DB_EXCEPTION.getCode());
            response.setMsg(OrderRetCode.DB_EXCEPTION.getMessage());
        }
        return response;

    }
}
